package com.qinghuan.threads.chapterFour;

import java.util.concurrent.atomic.AtomicLong;

/**
 * @Author: dubao
 * @Date: 2022/5/22 15:33
 * @Description:
 */

/**
 * 多线程使用AtomicLong统计0的个数，原子操作类
 * AtomicAdder比它更好一点
 */
public class Test4_1_1 {

    public static class Atomic {
        //创建Long型原子计数器
        private static AtomicLong atomicLong = new AtomicLong();
        //创建数据源
        private static Integer[] arrayOne = new Integer[]{0, 1, 2, 3, 0, 5, 6, 0, 56, 0};

        private static Integer[] arrayTwo = new Integer[]{10, 0, 1, 2, 3, 0, 5, 6, 0, 56, 0};

        public static void main(String[] args) throws InterruptedException {
            //线程one统计数组arrayOne中0的个数
            Thread threadOne = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<arrayOne.length; i++) {
                        if (arrayOne[i].equals(0)) {
                            atomicLong.incrementAndGet();
                        }
                    }
                }
            });
            //线程two统计数组arrayTwo中的个数
            Thread threadTwo = new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i=0; i<arrayTwo.length; i++) {
                        if (arrayTwo[i].equals(0)) {
                            atomicLong.incrementAndGet();
                        }
                    }
                }
            });

            threadOne.start();
            threadTwo.start();

            threadOne.join();
            threadTwo.join();

            System.out.println("count 0:" + atomicLong.get());
        }

    }

}
